package app.util.image.action
{
	import app.util.*;
	import app.util.image.calc.*;
	
	import flash.display.*;
	import flash.geom.*;
	
	
	public class HistogramAverageAction extends AbstractAction
	{
		
		public override function getDescription():String
		{
			return "Histogram Average";
		}
		
		public override function getActionedBitmapData():BitmapData
		{
			var old:BitmapData = Mediator.getCurrentBitmapData();			
			var w:int = old.width;
			var h:int = old.height;
			var ret:BitmapData = new BitmapData(w, h);
		
			var rArray:Array = new Array(BMPUtility.TOTAL_RANGE); 
			var gArray:Array  = new Array(BMPUtility.TOTAL_RANGE); 
			var bArray:Array  = new Array(BMPUtility.TOTAL_RANGE); 
			
			//Store the integration possibility
			var ir:Array = new Array(BMPUtility.TOTAL_RANGE); 
			var ig:Array  = new Array(BMPUtility.TOTAL_RANGE); 
			var ib:Array  = new Array(BMPUtility.TOTAL_RANGE); 		
			
			var nr:Array = new Array(BMPUtility.TOTAL_RANGE); 
			var ng:Array  = new Array(BMPUtility.TOTAL_RANGE); 
			var nb:Array  = new Array(BMPUtility.TOTAL_RANGE); 				
			var c:int, i:int, j:int;	
				
			for(c = 0; c < BMPUtility.TOTAL_RANGE; c++)
			{
				nr[c] = ng[c] = nb[c] = 
				ir[c] = ig[c] = ib[c] = 
				rArray[c] = gArray[c] = bArray[c] = 
				0;
			}
				
			for(i = 0; i < w; i++)
			{
				for(j = 0; j < h; j++)
				{
					var color:uint = old.getPixel(i, j);
					var r:uint = (color & 0x00ff0000) >> 16;
					var g:uint = (color & 0x0000ff00) >> 8;
					var b:uint = color & 0x000000ff;
					rArray[r] += 1;
					gArray[g] += 1;
					bArray[b] += 1;
				}
			}

			var total:int = w * h;
			for(c = 0; c < BMPUtility.TOTAL_RANGE; c++)
			{
				if(c > 0)
				{
					ir[c] = ir[c - 1] + rArray[c] / total;
					ig[c] = ig[c - 1] + gArray[c] / total;
					ib[c] = ib[c - 1] + bArray[c] / total;										
				}
				else
				{
					ir[c] = rArray[c] / total;
					ig[c] = gArray[c] / total;
					ib[c] = bArray[c] / total;
				}
				
				nr[c] = 255 * ir[c] + 0.5;
				ng[c] = 255 * ig[c] + 0.5;
				nb[c] = 255 * ib[c] + 0.5;
			}
			
			for(i = 0; i < w; i++)
			{
				for(j = 0; j < h; j++)
				{
					var oldColor:uint = old.getPixel(i, j);
					var oldR:uint = (oldColor & 0x00ff0000) >> 16;
					var oldG:uint = (oldColor & 0x0000ff00) >> 8;
					var oldB:uint = oldColor & 0x000000ff;
					var newColor:uint = 0;
					var newR:int = nr[oldR];
					var newG:int = ng[oldG];
					var newB:int = nb[oldB];
					newColor = (newR << 16 | newG << 8 | newB);
					ret.setPixel(i, j, newColor);
				}
			}
			
			return ret;
		}	
	}
}